var ssmap = {WKID:4326,spatialReference:null,isPano:false,isSinglePano:false,locatelayerId:null,drawType:99,tb:null,panoPoint:null};
require([
  "esri/map","esri/dijit/InfoWindow","esri/graphic","esri/geometry/Point","esri/SpatialReference","esri/tasks/GeometryService",
  "esri/tasks/LengthsParameters","esri/tasks/AreasAndLengthsParameters","esri/tasks/FindTask","esri/tasks/FindParameters",
  "esri/tasks/query","esri/tasks/QueryTask","esri/dijit/Print",
  "esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/ArcGISDynamicMapServiceLayer","esri/layers/FeatureLayer", 
  "esri/tasks/ClassBreaksDefinition", "esri/tasks/AlgorithmicColorRamp","esri/geometry/screenUtils",
  "esri/tasks/GenerateRendererParameters", "esri/tasks/GenerateRendererTask","esri/dijit/OverviewMap","esri/dijit/BasemapGallery","esri/dijit/Scalebar",
  "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleFillSymbol", 
  "esri/toolbars/draw","esri/toolbars/edit","esri/toolbars/navigation","esri/dijit/Measurement",
  "esri/dijit/PopupTemplate", "esri/dijit/Legend", "esri/config",
  "dojo/parser", "dojo/_base/array", "dojo/_base/lang","dojox/encoding/base64","esri/Color","dojo/on","dojo/dom-attr","dojo/dom-class","dojo/dom-style","dojo/query",
  "dojo/dom", "dojo/dom-construct","dijit/registry","dojo/json",
  "dojo/data/ItemFileReadStore", "dijit/form/FilteringSelect",
  "dgrid/OnDemandGrid",
  "dgrid/Selection", 
  "dgrid/extensions/Pagination", "dojo/store/Observable",
  "dojo/store/Memory", "dojo/store/Cache", "dojo/store/JsonRest", 
  "dojo/_base/declare", 
  "dijit/dijit-all", // dijit.*
  "dojox/layout/ResizeHandle",
  "dojox/widget/Dialog",
  "dojox/layout/FloatingPane",
  "dojo/dnd/Moveable",
  "dojo/fx",
  "cbtree/Tree",
  "cbtree/extensions/TreeStyling",
  "cbtree/store/ObjectStore",
  "cbtree/model/ForestStoreModel",
  "cbtree/model/TreeStoreModel",
  "dojox/layout/Dock",
  "dojo/domReady!"
], function(
  Map, InfoWindow,Graphic,Point,SpatialReference,GeometryService,
  LengthsParameters,AreasAndLengthsParameters,FindTask,FindParameters,
  Query, QueryTask,Print,
  ArcGISTiledMapServiceLayer, ArcGISDynamicMapServiceLayer,FeatureLayer, 
  ClassBreaksDefinition, AlgorithmicColorRamp,screenUtils,
  GenerateRendererParameters, GenerateRendererTask,OverviewMap,BasemapGallery,Scalebar,
  SimpleLineSymbol, SimpleFillSymbol, 
  Draw,Edit,Navigation,Measurement,
  PopupTemplate, Legend,esriConfig,
  parser, arrayUtils,lang,base64,Color,on,
  domAttr,domClass,domStyle,query,dom, domConstruct,registry,JSON,
  ItemFileReadStore, FilteringSelect,
  Grid, 
  Selection, Pagination,Observable,
  Memory, Cache,JsonRest,
  declare
) {
	parser.parse();
	 esriConfig.defaults.io.proxyUrl = appConfig.contPath+"/gis/proxy.jsp";
     esriConfig.defaults.io.alwaysUseProxy = false;
	var highlightSymbol=new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([78, 171, 214 ]), 4);
	var highlightFillSymbol= new SimpleFillSymbol(
            SimpleFillSymbol.STYLE_SOLID, 
            new SimpleLineSymbol(
              SimpleLineSymbol.STYLE_SOLID, 
              new Color([111, 0, 255]), 
              2
            ), 
            new Color([111, 0, 255, 0.45])
          );
	var carSymbol=esri.symbol.PictureMarkerSymbol(appConfig.contPath+"/images/gis/streetview-ani.gif", 25, 29);
	var monkeySymbol=esri.symbol.PictureMarkerSymbol(appConfig.contPath+"/images/gis/monkey/monkey_0.png", 89, 68);
	var lastPanoSymbol=esri.symbol.PictureMarkerSymbol(appConfig.contPath+"/images/gis/lastPano.png", 31, 42);
	var singlePanoSymbol=esri.symbol.PictureMarkerSymbol(appConfig.contPath+"/images/gis/icon_panorama.gif", 25, 25);
	var basemap = new ArcGISTiledMapServiceLayer(appConfig.gisPath+"/arcgis/rest/services/fsjt/bj/MapServer"); //底图
	var baseViewmap = new ArcGISTiledMapServiceLayer(appConfig.gisPath+"/arcgis/rest/services/fsjt/bj/MapServer"); //底图
	var sdRef = new ArcGISDynamicMapServiceLayer(appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer",{ "id": "facility" });  // 设施汇编
	var qhRef = new ArcGISDynamicMapServiceLayer(appConfig.gisPath+"/arcgis/rest/services/fsjt/qh/MapServer");  // 设施汇编
	var basedRefmap = new ArcGISDynamicMapServiceLayer(appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer"); //缩略图底图
	var diseaseSymbol=esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/tools/arrow-green.png?t=2322", 25, 25); //标识
	// 代理 GIS计算服务
	var geometryService = new GeometryService(appConfig.gisPath+"/arcgis/rest/services/Utilities/Geometry/GeometryServer");
	esriConfig.defaults.geometryService =geometryService;
	var carLayer = new esri.layers.FeatureLayer(appConfig.gisPath+"/arcgis/rest/services/fsjt/dl/MapServer/0",{  // 高亮含采集车数据
		mode: esri.layers.FeatureLayer.MODE_ONDEMAND,
		outFields:["道路编号","道路名称"]
	});
	var singlePanoLayer = new esri.layers.FeatureLayer(appConfig.gisPath+"/arcgis/rest/services/fsjt/dl/MapServer/1",{  // 高亮单点全景的影像
		mode: esri.layers.FeatureLayer.MODE_ONDEMAND,
		outFields:["*"]
	});
	var tb ,map,handlerMap,editToolbar;
	var progressBarDialog;


/**-------------------地图基础定义---------------------------*/
ssmap.map = map = new Map("ssmapdiv", { 
	//basemap: "osm",
    center:	new Point(113.041529 ,23.048709,new SpatialReference({ wkid: ssmap.WKID })), //中心点 113.041529 纬度: 23.048709
    zoom: 10,
    logo:false,
    nav:false,
    slider: true
  });
ssmap.map.addLayers([baseViewmap,qhRef,sdRef]);
addScalebar(ssmap.map);
ssmap.spatialReference = new SpatialReference({ wkid: ssmap.WKID }) ;
/**-------------------地图业务操作---------------------------*/
// 区域定位 
ssmap.pointLocation = function (lay,areacode) {
	  var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/bj/MapServer/"+lay;  
	  var queryTask=new QueryTask(searchurl);
	  var query = new Query();
		query.returnGeometry = true;
		query.outFields = [ "*" ];
		query.where = " StreetId = '" + areacode + "'"; 
		queryTask.execute(query,function (featureSet) {
			dojo.forEach(featureSet.features, function(graphic) {
				  graphic.setSymbol(highlightSymbol);
				  map.graphics.clear();
				  map.graphics.add(graphic);
				  setTimeout("ssmap.map.graphics.clear()",500)
				  map.centerAndZoom(graphic.geometry.getCentroid(),3);
			});
			});
	}
// 查询道路
ssmap.searchRoad = function (searchtext) {
	  var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer";  
	var findParams = new FindParameters(); 
        findParams.returnGeometry = true; 
        findParams.layerIds = [33,51,52,53]; 
        findParams.searchFields = ["道路名称","桥梁名称","所在道路名","结构形式","所在道路","隧道名称"];
        findParams.searchText = searchtext; 
        var findTask = new esri.tasks.FindTask(searchurl);
        function roadFormatter(item){
        	if(item.layerId == '33'){
        		return "<h4>" + item.index + ": " + item.dlbh + "</h4><p>" +
				item.dlm + "("+ item.qlgm +",  "+ item.qljg+")</p>";
        	} 
			return "<h4>" + item.index + ": " + item.dlbh + "</h4><p>" +
				item.dlm + "("+ item.dlfj +",  "+ item.xzjd+")</p>";
		}
        var columns = [{
            label: "查询结果",
            formatter: roadFormatter,
            field: "_item"
        }
        ]
        if(!ssmap.mapsearchGrid) {
        	ssmap.mapsearchGrid = new (declare([Grid,Pagination,Selection]))({
         	    selectionMode: "single",
                 idProperty:"id",
                 getBeforePut: false,
                 columns:columns
               }, "mapsearch");
        } else {
        	 ssmap.mapsearchGrid.set("columns",columns);
        }
        
        findTask.execute(findParams, function(findResults){
        	if(findResults.length==0){
        		return;
        	}
            map.graphics.clear();
            map.infoWindow.hide();
        	var data = arrayUtils.map(findResults, function(findResult,index) {
        		var graphic = findResult.feature;
//    				setGraphicSymbol(findResult.feature);
//    				summaryInfo(graphic);
//    				map.graphics.add(graphic);
                return {
                  // property names used here match those used when creating the dgrid
                  "layerId":findResult.layerId,
                  "index":index+1,
                  "id":findResult.feature.attributes["OBJECTID"],
                  "dlbh": findResult.feature.attributes["编码"]||findResult.feature.attributes["道路编号"]||findResult.feature.attributes["桥梁编码"]||findResult.feature.attributes["隧道代码"],
                  "dlm": findResult.feature.attributes["桥梁名称"]||findResult.feature.attributes["隧道名称"]||findResult.feature.attributes["道路名称"]||findResult.feature.attributes["所在道路名"]||findResult.feature.attributes["所在道路"], 
                  "xzqh": findResult.feature.attributes["区划"],
                  "xzjd": findResult.feature.attributes["街道"],
                  "dlfj": findResult.feature.attributes["道路分级"],
                  "dllx": findResult.feature.attributes["路面类型"],
                  "qlgm": findResult.feature.attributes["规模"],
                  "qljg": findResult.feature.attributes["结构形式"]
                }
              });
        	  var memStore = new Memory({ data: data });
        	  ssmap.mapsearchGrid.set("store", memStore);
        	  ssmap.mapsearchGrid.on("dgrid-select", function(evt){
            		var row =  evt.rows[0];
            		ssmap.map.infoWindow.hide();
            		var findParams = new esri.tasks.FindParameters();
            		var findTask = new esri.tasks.FindTask(searchurl);
            		findParams.returnGeometry = true; 
            		findParams.layerIds = [row.data.layerId]; 
            		findParams.searchFields = ["OBJECTID"];
            		findParams.searchText = row.id; 
            		findTask.execute(findParams, showSingleRoad);
            	});
        }); 
      
	}

//点击选中某条路
function showSingleRoad(results){
	dojo.forEach(results, function(result) { 
          var graphic = result.feature;	   
            setGraphicSymbol(graphic);
			summaryInfo(graphic);
			map.graphics.add(graphic);
		  var extent = getGeometryExtent(graphic.geometry);
		  var deferred  = map.setExtent(extent);
//			if( map.getLevel()<7) {
//				deferred = map.setExtent(extent,fit?);
//			} else {
//				deferred =
//			}
			deferred.then(function(value){
				var centrPoint =map.extent.getCenter();
				var screenPoint = map.toScreen(centrPoint);
				map.infoWindow.setTitle(graphic.getTitle());
		        map.infoWindow.setContent(graphic.getContent());
		        map.infoWindow.show(centrPoint,map.getInfoWindowAnchor(screenPoint));
		        map.infoWindow.setFeatures([graphic]);
			  });
        }); 
}
//显示全生命周期显示框
ssmap.detailInfo =function detailInfo(roadCode) {
    var titlePane = new dojox.widget.Dialog({
    	dimensions:[830,500],
    	draggable:true,
    	modal:true,
    	parseOnLoad:true,
		onHide : function() {
			this.destroyRecursive();
		},
		sizeToViewport:true,
    	refreshOnShow:true,
		sizeMethod:"combine",
        title:'道路概况',
        href:'/fsjt/mp/projectinfo!info.action?roadCode='+roadCode
      });
     // titlePane.placeAt(ssmap.map.root,"last");
      titlePane.startup();
      titlePane.show();
	  //showVisionByLngLat(point.x,point.y);
};


//显示设施量统计汇总
ssmap.detailTotalRoadInfo =function detailTotalRoadInfo(roadCode) {
	var node = document.createElement('div');
	dojo.body().appendChild(node);
    var floatingPane = new dojox.layout.FloatingPane({
    	draggable:true,
    	closable :true,
    	resizable:false,
    	maxable:false,
		onHide : function() {
			this.destroyRecursive();
		},
    	dockable:false,
    	refreshOnShow:true,
    	href:'/fsjt/dl/roadbasic!view.action?roadCode='+roadCode,
    	style:"width:300px; height:550px;padding:5px;z-index: 9999;top: 0px;left:0px;overflow: hidden;z-index:999 ",
    	title:'道路概况'
      },node);
      floatingPane.startup();

	  //showVisionByLngLat(point.x,point.y);
};

// 案件查询
ssmap.searchbh = function (searchtext) {
	searchtext = encodeURIComponent(searchtext);
	var listStore   = Observable(Cache(JsonRest({
		target:appConfig.contPath+"/yh/disease/damagedisease!listMap.action?filter_LIKES_landmark_OR_roundName_OR_describe="+searchtext,
		idProperty: "id"
	}), new Memory()));
	var  columns=[{
        label: "案件号",
        className:"index",
        get: function(object){
            return object.caseNumber;
        },
        field: "index"
    },{
        label: "查询结果",
        formatter: function(item){
      		var x =  item.blat;
      		var y =  item.blon;
      		if(x&&y){
      			return "<h4>" + vSting(item.caseClass) + " " + vSting(item.caseGroup) + ":</h4><p> " + vSting(item.landmark) + "</p><p>" +
      					vSting(item.describe) + "</p><img src='"+appConfig.contPath+"/images/gis/marker.png'/>" ;
      		} else {
        	return "<h4>" + vSting(item.caseClass) + " " + vSting(item.caseGroup) + ":</h4><p> " + vSting(item.landmark) + "</p><p>" +
			item.describe + "</p><p style='color: red;'>无坐标</p>" ;
      		}
        },
        field: "_item"
    }
    ];
    if(!ssmap.mapsearchGrid) {
    	var ListGrid = declare([Grid,Pagination,Selection]);
    	ssmap.mapsearchGrid = new ListGrid({
     	     selectionMode: "single",
             idProperty:"id",
             getBeforePut: false,
             store:listStore,
             loadingMessage:'正在查询', 
             pagingLinks: true,
             pagingTextBox: true,
             firstLastArrows: true,
             columns:columns
           }, "mapsearch");
    }else {
    	 ssmap.mapsearchGrid.set("columns",columns);
    	 ssmap.mapsearchGrid.set("store",listStore);
    }
	  ssmap.mapsearchGrid.on("dgrid-select", function(evt){
  		var row =  evt.rows[0];
  		var x =  row.data.blat;
  		var y =  row.data.blon;
  		if(x&&y){
	  		var pt = new Point(x, y,ssmap.spatialReference);
	  		
	  		var graphic = new Graphic(pt,new esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/gis/marker.png",21,25));
	 	 	//setGraphicSymbol(graphic)
	 	    map.graphics.add(graphic);
	 		var infoTemplate = new esri.InfoTemplate(vSting(row.data.caseNumber), "<h4>" + vSting(row.data.caseClass) + " " + vSting(row.data.caseGroup) + ":</h4><p> " + vSting(row.data.landmark) + "</p><p>" +
	 		row.data.describe + "</p><a title='案件详情'  href='"+appConfig.contPath +"/yh/disease/damagedisease!getIndex.action?id="+row.data.id+"' target='_blank' style='cursor:hand;color:red'>案件详情</a>&nbsp;&nbsp;&nbsp;&nbsp;");
	 		graphic.setInfoTemplate(infoTemplate);
			 var deferred ;
				if( map.getLevel()<7) {
					deferred = map.centerAndZoom(pt,7);
				} else {
					deferred =map.centerAt(pt);
				}
				deferred.then(function(value){
					var centrPoint =map.extent.getCenter();
					var screenPoint = map.toScreen(centrPoint);
					map.infoWindow.setTitle(graphic.getTitle());
			        map.infoWindow.setContent(graphic.getContent());
			        map.infoWindow.show(centrPoint,map.getInfoWindowAnchor(screenPoint));
				  });
  		} 
  	});
}
//案件图层
ssmap.locationbh =function (){
	require(["dojo/request/xhr"],function(xhr) {
			 xhr(appConfig.contPath+"/yh/disease/damagedisease!listMap.action?page.pageSize=1000",{
				 method:'get', 
                 handleAs: "json"
              }).then(function(data){
            	  dojo.forEach(data, function(item) { 
            	  		var x =  item.blat;
            	  		var y =  item.blon;
            	  		if(x&&y){
            		  		var pt = new Point(x, y,ssmap.spatialReference);
            		  		var graphic = new Graphic(pt,new esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/gis/marker.png",21,25));
            		 	 	//setGraphicSymbol(graphic)
            		  		var infoTemplate = new esri.InfoTemplate(item.caseNumber, "<h4>" + item.caseClass + " " + item.caseGroup + ":</h4><p> " + item.landmark + "</p><p>" +
            		  				item.describe + "</p><a title='案件详情'  href='"+appConfig.contPath +"/yh/disease/damagedisease!getIndex.action?id="+item.id+"' target='_blank' style='cursor:hand;color:red'>案件详情</a>&nbsp;&nbsp;&nbsp;&nbsp;");
            		  		graphic.setInfoTemplate(infoTemplate);
            		 	    map.graphics.add(graphic);
//            				if( map.getLevel()<7) {
//            				    map.centerAndZoom(pt,7);
//            				} else {
//            					map.centerAt(pt);
//            				}
            	  		}
            		  
            	  });
              });
	  });
	
}

//8888888888888888888888888888数字城管

//案件查询
ssmap.searchcg = function (searchtext) {
	searchtext = encodeURIComponent(searchtext);
	var listStore   = Observable(Cache(JsonRest({
		target:appConfig.contPath+"/yh/digital/digitalmanager!listMap.action?filter_LIKES_landmark_OR_roundName_OR_describe="+searchtext,
		idProperty: "id"
	}), new Memory()));
	var  columns=[{
        label: "案件号",
        className:"index",
        get: function(object){
            return object.caseNumber;
        },
        field: "index"
    },{
        label: "查询结果",
        formatter: function(item){
      		var x =  item.blat;
      		var y =  item.blon;
      		if(x&&y){
      			return "<h4>" + vSting(item.caseClass) + " " + vSting(item.caseGroup) + ":</h4><p> " + vSting(item.landmark) + "</p><p>" +
      					vSting(item.describe) + "</p><img src='"+appConfig.contPath+"/images/gis/marker.png'/>" ;
      		} else {
        	return "<h4>" + vSting(item.caseClass) + " " + vSting(item.caseGroup) + ":</h4><p> " + vSting(item.landmark) + "</p><p>" +
			item.describe + "</p><p style='color: red;'>无坐标</p>" ;
      		}
        },
        field: "_item"
    }
    ];
    if(!ssmap.mapsearchGrid) {
    	var ListGrid = declare([Grid,Pagination,Selection]);
    	ssmap.mapsearchGrid = new ListGrid({
     	     selectionMode: "single",
             idProperty:"id",
             getBeforePut: false,
             store:listStore,
             loadingMessage:'正在查询', 
             pagingLinks: true,
             pagingTextBox: true,
             firstLastArrows: true,
             columns:columns
           }, "mapsearch");
    }else {
    	 ssmap.mapsearchGrid.set("columns",columns);
    	 ssmap.mapsearchGrid.set("store",listStore);
    }
	  ssmap.mapsearchGrid.on("dgrid-select", function(evt){
  		var row =  evt.rows[0];
  		var x =  row.data.blat;
  		var y =  row.data.blon;
  		if(x&&y){
	  		var pt = new Point(x, y,ssmap.spatialReference);
	  		
	  		var graphic = new Graphic(pt,new esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/gis/marker.png",21,25));
	 	 	//setGraphicSymbol(graphic)
	 	    map.graphics.add(graphic);
	 		var infoTemplate = new esri.InfoTemplate(vSting(row.data.caseNumber), "<h4>" + vSting(row.data.caseClass) + " " + vSting(row.data.caseGroup) + ":</h4><p> " + vSting(row.data.landmark) + "</p><p>" +
	 		row.data.describe + "</p><a title='案件详情'  href='"+appConfig.contPath +"/yh/disease/damagedisease!getIndex.action?id="+row.data.id+"' target='_blank' style='cursor:hand;color:red'>案件详情</a>&nbsp;&nbsp;&nbsp;&nbsp;");
	 		graphic.setInfoTemplate(infoTemplate);
			 var deferred ;
				if( map.getLevel()<7) {
					deferred = map.centerAndZoom(pt,7);
				} else {
					deferred =map.centerAt(pt);
				}
				deferred.then(function(value){
					var centrPoint =map.extent.getCenter();
					var screenPoint = map.toScreen(centrPoint);
					map.infoWindow.setTitle(graphic.getTitle());
			        map.infoWindow.setContent(graphic.getContent());
			        map.infoWindow.show(centrPoint,map.getInfoWindowAnchor(screenPoint));
				  });
  		} 
  	});
}
//案件图层
ssmap.locationcg =function (){
	require(["dojo/request/xhr"],function(xhr) {
			 xhr(appConfig.contPath+"/yh/digital/digitalmanager!listMap.action?page.pageSize=1000",{
				 method:'get', 
                 handleAs: "json"
              }).then(function(data){
            	  dojo.forEach(data, function(item) { 
            	  		var x =  item.blat;
            	  		var y =  item.blon;
            	  		if(x&&y){
            		  		var pt = new Point(x, y,ssmap.spatialReference);
            		  		var graphic = new Graphic(pt,new esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/gis/marker.png",21,25));
            		 	 	//setGraphicSymbol(graphic)
            		  		var infoTemplate = new esri.InfoTemplate(item.caseNumber, "<h4>" + item.caseClass + " " + item.caseGroup + ":</h4><p> " + item.landmark + "</p><p>" +
            		  				item.describe + "</p><a title='案件详情'  href='"+appConfig.contPath +"/yh/disease/damagedisease!getIndex.action?id="+item.id+"' target='_blank' style='cursor:hand;color:red'>案件详情</a>&nbsp;&nbsp;&nbsp;&nbsp;");
            		  		graphic.setInfoTemplate(infoTemplate);
            		 	    map.graphics.add(graphic);
//            				if( map.getLevel()<7) {
//            				    map.centerAndZoom(pt,7);
//            				} else {
//            					map.centerAt(pt);
//            				}
            	  		}
            		  
            	  });
              });
	  });
	
}


//--------路政许可图层-------------------//

//施工许可
ssmap.locationpowa =function (){
	require(["dojo/request/xhr"],function(xhr) {
			 xhr(appConfig.contPath+"/yh/high/highwaysdig!listMap.action?page.pageSize=1000",{
				 method:'get', 
                 handleAs: "json"
              }).then(function(data){
            	  dojo.forEach(data, function(item) { 
            	  		var x =  item.lon||item.blat;
            	  		var y =  item.lat||item.blon;
            	  		if(x&&y){
            		  		var pt = new Point(x, y,ssmap.spatialReference);
            		  		var graphic = new Graphic(pt,new esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/gis/marker-blue.png",21,25));
            		 	 	//setGraphicSymbol(graphic)
            		  		var infoTemplate = new esri.InfoTemplate(item.caseNumber, "<h4>  " + item.subordinateOrg + ":</h4><p> " + item.landmark + "</p><p> 许可期限:" +
            		  				item.caseTime + "到:"+item.dealDate+"</p><a title='许可详情'  href='"+appConfig.contPath +"/yh/high/highwaysdig!getIndex.action?id="+item.id+"' target='_blank' style='cursor:hand;color:red'>许可详情</a>&nbsp;&nbsp;&nbsp;&nbsp;");
            		  		graphic.setInfoTemplate(infoTemplate);
            		 	    map.graphics.add(graphic);
            	  		}
            		  
            	  });
              });
	  });
	
}
//施工许可
ssmap.searchpowa = function (searchtext) {
	searchtext = encodeURIComponent(searchtext);
	var listStore   = Observable(Cache(JsonRest({
		target:appConfig.contPath+"/yh/high/highwaysdig!listMap.action?filter_LIKES_landmark_OR_roundName_OR_describe="+searchtext,
		idProperty: "id"
	}), new Memory()));
	var  columns=[{
        label: "案件号",
        className:"index",
        get: function(object){
            return object.caseNumber;
        },
        field: "index"
    },{
        label: "查询结果",
        formatter: function(item){
  	  		var x =  item.lon||item.blat;
	  		var y =  item.lat||item.blon;
      		if(x&&y){
      			return "<h4>" + item.subordinateOrg + ":</h4><p> " + item.landmark + "</p>许可期限:" +
            		  				item.caseTime + "到:"+item.dealDate+"</p><img src='"+appConfig.contPath+"/images/gis/marker-blue.png'/>" ;
      		} else {
        	return "<h4>" + item.subordinateOrg + ":</h4><p> " + item.landmark + "</p>许可期限:" +
            		  				item.caseTime + "到:"+item.dealDate+"</p>无坐标</p>" ;
      		}
        },
        field: "_item"
    }
    ];
    if(!ssmap.mapsearchGrid) {
    	var ListGrid = declare([Grid,Pagination,Selection]);
    	ssmap.mapsearchGrid = new ListGrid({
     	     selectionMode: "single",
             idProperty:"id",
             getBeforePut: false,
             store:listStore,
             loadingMessage:'正在查询', 
             pagingLinks: true,
             pagingTextBox: true,
             firstLastArrows: true,
             columns:columns
           }, "mapsearch");
    }else {
    	 ssmap.mapsearchGrid.set("columns",columns);
    	 ssmap.mapsearchGrid.set("store",listStore);
    }
	  ssmap.mapsearchGrid.on("dgrid-select", function(evt){
  		var row =  evt.rows[0];
  		var x =  row.data.lon||row.data.blat;
  		var y =  row.data.lat||row.data.blon;
  		if(x&&y){
	  		var pt = new Point(x, y,ssmap.spatialReference);
	  		var graphic = new Graphic(pt,new esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/gis/marker-blue.png",21,25));
	 	 	//setGraphicSymbol(graphic)
	  		var infoTemplate = new esri.InfoTemplate(row.data.caseNumber, "<h4>  " + row.data.subordinateOrg + ":</h4><p> " + row.data.landmark + "</p><p> 许可期限:" +
	  				row.data.caseTime + "到:"+row.data.dealDate+"</p><a title='许可详情'  href='"+appConfig.contPath +"/yh/high/highwaysdig!getIndex.action?id="+row.data.id+"' target='_blank' style='cursor:hand;color:red'>许可详情</a>&nbsp;&nbsp;&nbsp;&nbsp;");
	  		graphic.setInfoTemplate(infoTemplate);
	 	    map.graphics.add(graphic);
			 var deferred ;
				if( map.getLevel()<7) {
					deferred = map.centerAndZoom(pt,7);
				} else {
					deferred =map.centerAt(pt);
				}
				deferred.then(function(value){
					var centrPoint =map.extent.getCenter();
					var screenPoint = map.toScreen(centrPoint);
					map.infoWindow.setTitle(graphic.getTitle());
			        map.infoWindow.setContent(graphic.getContent());
			        map.infoWindow.show(centrPoint,map.getInfoWindowAnchor(screenPoint));
				  });
  		} 
  	});
}

//--------投诉图层-------------------//

//案件图层
ssmap.locationtousu =function (){
	require(["dojo/request/xhr"],function(xhr) {
			 xhr(appConfig.contPath+"/yh/public/publiccomplaints!listMap.action?page.pageSize=1000",{
				 method:'get', 
               handleAs: "json"
            }).then(function(data){
          	  dojo.forEach(data, function(item) { 
          	  		var x =  item.lon||item.blat;
          	  		var y =  item.lat||item.blon;
          	  		if(x&&y){
          		  		var pt = new Point(x, y,ssmap.spatialReference);
          		  		var graphic = new Graphic(pt,new esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/gis/marker-gold.png",21,25));
          		 	 	//setGraphicSymbol(graphic)
          		  		var infoTemplate = new esri.InfoTemplate(item.caseNumber, "<h4>  " + item.disposeOrg + ":</h4><p> " + item.landmark + "</p><p> 投诉内容:" +
          		  				item.describe + "</p><a title='投诉详情'  href='"+appConfig.contPath +"/yh/public/publiccomplaints!getIndex.action?id="+item.id+"' target='_blank' style='cursor:hand;color:red'>投诉详情</a>&nbsp;&nbsp;&nbsp;&nbsp;");
          		  		graphic.setInfoTemplate(infoTemplate);
          		 	    map.graphics.add(graphic);
          	  		}
          		  
          	  });
            });
	  });
	
}

//投诉
ssmap.searchtousu = function (searchtext) {
	searchtext = encodeURIComponent(searchtext);
	var listStore   = Observable(Cache(JsonRest({
		target:appConfig.contPath+"/yh/public/publiccomplaints!listMap.action?filter_LIKES_landmark_OR_roundName_OR_describe="+searchtext,
		idProperty: "id"
	}), new Memory()));
	var  columns=[{
        label: "案件号",
        className:"index",
        get: function(object){
            return object.caseNumber;
        },
        field: "index"
    },{
        label: "查询结果",
        formatter: function(item){
  	  		var x =  item.lon||item.blat;
	  		var y =  item.lat||item.blon;
      		if(x&&y){
      			return "<h4>" + item.subordinateOrg + ":</h4><p> " + item.landmark  + "</p>投诉内容:" +
      			item.describe +"</p><img src='"+appConfig.contPath+"/images/gis/marker-gold.png'/>" ;
      		} else {
        	return "<h4>" + item.subordinateOrg + ":</h4><p> " + item.landmark  + "</p>投诉内容:" +
      			item.describe +"</p>无坐标</p>" ;
      		}
        },
        field: "_item"
    }
    ];
    if(!ssmap.mapsearchGrid) {
    	var ListGrid = declare([Grid,Pagination,Selection]);
    	ssmap.mapsearchGrid = new ListGrid({
     	     selectionMode: "single",
             idProperty:"id",
             getBeforePut: false,
             store:listStore,
             loadingMessage:'正在查询', 
             pagingLinks: true,
             pagingTextBox: true,
             firstLastArrows: true,
             columns:columns
           }, "mapsearch");
    }else {
    	 ssmap.mapsearchGrid.set("columns",columns);
    	 ssmap.mapsearchGrid.set("store",listStore);
    }
	  ssmap.mapsearchGrid.on("dgrid-select", function(evt){
  		var row =  evt.rows[0];

  		var x =  row.data.lon||row.data.blat;
  		var y =  row.data.lat||row.data.blon;
  		if(x&&y){
	  		var pt = new Point(x, y,new SpatialReference({ wkid: ssmap.WKID }));
	  		var graphic = new Graphic(pt,new esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/gis/marker-gold.png",21,25));
	 	 	//setGraphicSymbol(graphic)
	  		var infoTemplate = new esri.InfoTemplate(row.data.caseNumber, "<h4>  " + row.data.subordinateOrg + ":</h4><p> " + row.data.landmark + "</p><p> 投诉内容:" +
	  				row.data.describe+"</p><a title='投诉详情'  href='"+appConfig.contPath +"/yh/public/publiccomplaints!getIndex.action?id="+row.data.id+"' target='_blank' style='cursor:hand;color:red'>投诉详情</a>&nbsp;&nbsp;&nbsp;&nbsp;");
	  		graphic.setInfoTemplate(infoTemplate);
	 	    map.graphics.add(graphic);
			 var deferred ;
				if( map.getLevel()<7) {
					deferred = map.centerAndZoom(pt,7);
				} else {
					deferred =map.centerAt(pt);
				}
				deferred.then(function(value){
					var centrPoint =map.extent.getCenter();
					var screenPoint = map.toScreen(centrPoint);
					map.infoWindow.setTitle(graphic.getTitle());
			        map.infoWindow.setContent(graphic.getContent());
			        map.infoWindow.show(centrPoint,map.getInfoWindowAnchor(screenPoint));
				  });
  		} 
  	});
}
//--------工程图层-------------------//

//案件图层
ssmap.locationproject =function (){
	require(["dojo/request/xhr"],function(xhr) {
			 xhr(appConfig.contPath+"/mp/projectinfo.action?page.pageSize=1000&filter_NOTNULLS_geoLocation=1",{
				 method:'get', 
             handleAs: "json"
          }).then(function(data){
        	  dojo.forEach(data, function(item) { 
        	  		var geoLocation =  item.geoLocation;
        	  		if(geoLocation){
        		  		var polygon = new esri.geometry.Polygon(JSON.parse(geoLocation));
        		  		var graphic = new Graphic(polygon,new esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/gis/marker-green.png",21,25));
        		  		//var graphic = new Graphic(pt,new esri.symbol.PictureMarkerSymbol(appConfig.contPath +"/images/gis/marker-gold.png",21,25));
        		 	 	//setGraphicSymbol(graphic)
        		  		var infoTemplate = new esri.InfoTemplate(item.projName, "<h4>  " + item.roadName + ":</h4><p> " + item.landmark + "</p><p> 投诉内容:" +
        		  				item.describe + "</p><a title='工程详情'  href='"+appConfig.contPath +"/mp/projectinfo!getDetail.action?id="+item.id+"' target='_blank' style='cursor:hand;color:red'>许可详情</a>&nbsp;&nbsp;&nbsp;&nbsp;");
        		  		graphic.setInfoTemplate(infoTemplate);
        		 	    map.graphics.add(graphic);
//        				if( map.getLevel()<7) {
//        				    map.centerAndZoom(pt,7);
//        				} else {
//        					map.centerAt(pt);
//        				}
        	  		}
        		  
        	  });
          });
	  });
	
}

ssmap.locationYewu  =function (items){
	map.graphics.clear();
	 dojo.forEach(items, function(item) {
		 var noid =item.id;
		 	if("cases"==noid){
				ssmap.locationbh();
		 	} else if("powa"==noid){
				ssmap.locationpowa();
			 } else if("tousu"==noid){
				ssmap.locationtousu();
			 } else if("project"==noid){
				ssmap.locationproject();
			 }else if("cases"==noid){
				ssmap.locationcg();
			 }
		 
	 });
	
	
}
//---------------------设施信息查询-----------------------------//
//绑定概要信息
function summaryInfo(graphic){
	var point  = getGeometryCenter(graphic.geometry);
	var dlbh = graphic.attributes["编码"]||graphic.attributes["道路编号"]||graphic.attributes["桥梁编码"]||graphic.attributes["隧道代码"];
	var roadName = graphic.attributes["桥梁名称"]||graphic.attributes["道路名称"]||graphic.attributes["隧道名称"]||graphic.attributes["所在道路名"]||graphic.attributes["所在道路"]
	infoTemplate = new esri.InfoTemplate("概要信息", ""+(roadName)
			+"&nbsp;&nbsp;&nbsp;&nbsp;<a title='道路详情' onclick='ssmap.detailInfo(\""+dlbh+"\")' style='cursor:hand;color:red'>全生命周期</a>&nbsp;&nbsp;&nbsp;&nbsp;<a title='道路设施汇总' onclick='ssmap.detailTotalRoadInfo(\""+dlbh+"\")' style='cursor:hand;color:red'>设施统计汇总</a>&nbsp;&nbsp;&nbsp;&nbsp;");
	graphic.setInfoTemplate(infoTemplate);
}


//** 左边树结构右键查询
ssmap.createMenu = function createMenu(){
	function fLocateClick(){
		var tn = dijit.byNode(pMenu.currentTarget);
		ssmap.showLocatelayer(tn.item.id)
	}
	function fSearchClick(){
		var tn = dijit.byNode(pMenu.currentTarget);
		var arcSearch = registry.byId("arcSearch");
		ssmap.listfacilityGrid(arcSearch.value,tn.item.id,tn.item.name);
	}
	function fTjClick(){
		var tn = dijit.byNode(pMenu.currentTarget);
		var districtSearch = registry.byId("districtSearch");
		var subdistrictSearch = registry.byId("subdistrictSearch");
		var roadSearch = registry.byId("roadSearch");
		ssmap.tjfacilityGrid(districtSearch,subdistrictSearch,roadSearch,tn.item.id,tn.item.name);
	}
	var pMenu = new dijit.Menu({targetNodeIds:["checkBoxTree"], id:"progMenu", selector: ".dijitTreeNode"});
	pMenu.addChild(new dijit.MenuItem({label:"定位高亮",iconClass:"dijitIconfix",onClick:fLocateClick}));
	pMenu.addChild(new dijit.MenuSeparator());
	var pSubMenu = new dijit.Menu({parentMenu:pMenu });
	var form = new dijit.layout.ContentPane({}); //
	form.addChild(new dijit.form.TextBox({id:"arcSearch"}));
	form.addChild(new dijit.form.Button({label:"查询",iconClass:"dijitIconSearch",onClick:fSearchClick}));
	pSubMenu.addChild(form);
	pMenu.addChild(new dijit.PopupMenuItem({label:"查询",iconClass:"dijitIconFilter",popup:pSubMenu}));
	
//	//统计
//	pMenu.addChild(new dijit.MenuSeparator());
//	var pTjSubMenu = new dijit.Menu({parentMenu:pMenu });
//	var form = new dijit.layout.ContentPane({});
//	form.addChild(new dijit.form.TextBox({id:"districtSearch"})); //
//	form.addChild(new dijit.form.TextBox({id:"subdistrictSearch"})); //
//	form.addChild(new dijit.form.TextBox({id:"roadSearch"})); //
//	form.addChild(new dijit.form.Button({label:"统计",iconClass:"dijitIconSearch",onClick:fTjClick}));
//	pTjSubMenu.addChild(form);
//	pMenu.addChild(new dijit.PopupMenuItem({label:"统计",iconClass:"dijitIconChart",popup:pTjSubMenu}));
	pMenu.startup();
}
// 
ssmap.cleanLocate = function () {
	if(ssmap.searchLocateevt){
		ssmap.searchLocateevt.remove();
	}
}
//动态查询
ssmap.showLocatelayer =function showLocatelayer(layId){
	if(ssmap.searchLocateevt){
		ssmap.searchLocateevt.remove();
	}
	ssmap.locatelayerId= layId;
	searchLocate();
    ssmap.searchLocateevt =on(map,"extent-change",searchLocate);
}

function getGeometryCenter (geometry) {
	 var point;
	  switch(geometry.type){
	    case "point":
	    	point =geometry;
	      break;
	    case "polyline":
	    	point =geometry.getExtent().getCenter();
	      break;
	    case "polygon":
	    	point =geometry.getExtent().getCenter();
	      break;
	  }
	  return point;
}

function getGeometryExtent (geometry) {
	 var extent;
	  switch(geometry.type){
	    case "point":
	    	extent =geometry;
	      break;
	    default: 
	    	extent =geometry.getExtent();
	  }
	  return extent;
}
// 设置高亮的模式
function setGraphicSymbol(graphic) {
	var geometry  = graphic.geometry;
	  switch(geometry.type){
	    case "point":
	    	 graphic.setSymbol(diseaseSymbol);
	      break;
	    case "polyline":
	    	 graphic.setSymbol(highlightSymbol);
	      break;
	    case "polygon":
	    	graphic.setSymbol(highlightFillSymbol);
	      break;
	  }  
}
// 图层显示
function setFeatureSetInMap (features,showInfoWindow,isCenter) {
	var showfeature;
		for (var i=0;i<features.length;i++)
		{
			var graphic = features[i];
			setGraphicSymbol(graphic);
			var roadName = graphic.attributes["道路名称"]|| graphic.attributes["所在道路"]||graphic.attributes["所在道路名称"]||graphic.attributes["所在道路名"]
			var infoTemplate = new esri.InfoTemplate(roadName,  buildTemplateColumns(graphic.attributes));
			  graphic.setInfoTemplate(infoTemplate);
			  map.graphics.add(graphic);
			  // 如果需要实时展示infowindow 展示最后一个
			if(showInfoWindow && (i ==(features.length -1))){
				showfeature = graphic;
			}
		}	
		if(showInfoWindow && showfeature){
			var zoomDeferred = new dojo.Deferred();
			 if(map.getLevel()<17) { 
				 zoomDeferred = map.setZoom(17);
			 } else {
				 zoomDeferred.resolve();
			 }
			zoomDeferred.then(function(){
				 var extent = map.extent;
				 var width =  map.width;
				 var height = map.height
				 var point = getGeometryCenter(showfeature.geometry);
				 if(!isCenter){
					 var screenPoint = map.toScreen(point);
					 centrPoint = map.toMap(screenPoint.offset(0,-260)); 
				 } else {
					 centrPoint =point;
				 }
				var deferred = map.centerAt(centrPoint);
					deferred.then(function(value){
						map.infoWindow.setTitle(showfeature.getTitle());
				        map.infoWindow.setContent(showfeature.getContent());
				        map.infoWindow.setFeatures([graphic]);
				        map.infoWindow.show(point,map.getInfoWindowAnchor(map.toScreen(point)));
					  });
			});
		 }


}

function buildTemplateColumns(attributes) {
    var template  = "详情如下  (长度单位:米,面积单位:平方米)";
    for (var attribute in attributes) {
        if (attributes.hasOwnProperty(attribute)) {
        	var label = attribute;
            if (attribute === "Shape") {
            	continue;
            } else if (attribute === "OBJECTID") {
            	continue;
            }
            else if (attribute === "照片") {
            	continue;
            }
            else if (attribute === "采集日期") {
            	continue;
            }else if(attribute === "SHAPE_Leng"||attribute === "Shape_Le_1"||attribute === "Shape_Length" ){
            	continue;
            }else if(attribute === "Shape_Leng"){
            	label ="图形长度";
            }else if(attribute === "Shape_Area"){
            	label ="图形面积";
            }
            template = template +"<br><b>"+label+":</b>　";
            var v =attributes[attribute];
            if(isInteger(v)){
              template = template +"${"+attribute+":NumberFormat(places:0)}";
            }
            else if(isDouble(v)) {
              template = template +"${"+attribute+":NumberFormat(places:2)}";
            }
            else {
              template = template +"${"+attribute+"}";
            }
        }
    }
    return template;
}
//重复桥梁的问题
function searchrepeatBridge(){
	  var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer/29";  
	  var queryTask=new QueryTask(searchurl);
	  var query = new Query();
		query.returnGeometry = true;
		query.geometry=map.extent;
		query.outFields = [ "*" ];
		query.where = "1 = 1"; 
		map.graphics.clear();
		queryTask.execute(query,function (featureSet) {
			var features =featureSet.features;
				for (var i=0;i<features.length;i++)
				{
					var graphic = features[i];
					setGraphicSymbol(graphic);
					var roadName = graphic.attributes["道路名称"]|| graphic.attributes["所在道路"]||graphic.attributes["所在道路名称"]
					var infoTemplate = new esri.InfoTemplate(roadName,  buildTemplateColumns(graphic.attributes));
					  graphic.setInfoTemplate(infoTemplate);
					  map.graphics.add(graphic);
				   var glid = graphic.attributes["JOIN_FID"];
				   
				   var queryTask2=new QueryTask(appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer/34");
					  var query = new Query();
						query.returnGeometry = true;
						query.geometry=map.extent;
						query.outFields = [ "*" ];
						query.where = "FID  = " +glid; 
						queryTask2.execute(query,function (featureSet) {
							var features =featureSet.features;
							for (var i=0;i<features.length;i++)
							{
								var graphic = features[i];
								setGraphicSymbol(graphic);
								var roadName = graphic.attributes["公路桥名称"]|| graphic.attributes["所在道路"]||graphic.attributes["所在道路名称"]
								var infoTemplate = new esri.InfoTemplate(roadName,  buildTemplateColumns(graphic.attributes));
								  graphic.setInfoTemplate(infoTemplate);
								  map.graphics.add(graphic);
							}
						});
				}	

		});
}
// 查询所有视野范围的设施
function searchLocate() {
	   if(ssmap.locatelayerId == 29){
		   
		   searchrepeatBridge();
		   return;
	   }
	  var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer/"+ ssmap.locatelayerId;  
	  var queryTask=new QueryTask(searchurl);
	  var query = new Query();
		query.returnGeometry = true;
		query.geometry=map.extent;
		query.outFields = [ "*" ];
		query.where = "1 = 1"; 
		map.graphics.clear();
		queryTask.execute(query,function (featureSet) {
			setFeatureSetInMap(featureSet.features);
		});
	}
//对地图进行初始化
ssmap.listfacilityGrid =function listfacilityGrid(searchText,searchLayerId,searchLayerName) {
	if(!searchText){
		listfacilityAll(searchLayerId,searchLayerName);
		return;
	} 
	searchtext = encodeURIComponent(searchtext);
	   progressBarDialog = dojoProgressBar("正在查询");
	   var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer/";
	   var queryTask = new QueryTask(searchurl+searchLayerId);
	   var findParams = new FindParameters(); 
       findParams.returnGeometry = false; 
       findParams.layerIds = [searchLayerId]; 
       findParams.searchFields = ["道路名称","道路编号","路面类型","所在道路名","所在道路名称","桥梁名称","公路桥梁名称","线路名称","所在道路","编码","行政区划","所在区划","街道","区划"];
	   findParams.searchText = searchText; 
	   var findTask = new FindTask(searchurl);
			map.graphics.clear();
			findTask.execute(findParams, function(findResults){
	        	if(findResults.length==0){
	        		progressBarDialog.hide();
	        		return;
	        	}
	        	var attributes  =findResults[0].feature.attributes;
	        	var columns = buildColumns(attributes);
	        	var data = arrayUtils.map(findResults, function(findResult,index) {
	        		var feature = findResult.feature;
	        		 return feature.attributes;
	        	});
	            var memStore = new Memory({
	                data: data,
	                idProperty: "OBJECTID"
	              });
				var dataGrid = new (declare([Grid, Selection]))({
				     bufferRows: Infinity,
				     pagingLinks: true,
	                 pagingTextBox: true,
	                 firstLastArrows: false,
	                 style:" height:300px;",
	                 pageSizeOptions: [10, 15, 25],
				     columns: columns,
			    	 id:"listfacilityGrid",
				     selectionMode: "single",
				     "class": "listfacilityGrid"
				});
				var node = document.createElement('div');
				dojo.body().appendChild(node);
				var floatingPane =dijit.byId("floatingPane");
				if(floatingPane) {
					floatingPane.destroyRecursive();
				}
			    var floatingPane = new dojox.layout.FloatingPane({
			    	draggable:true,
			    	closable :true,
			    	resizable:false,
			    	id:"floatingPane",
			    	maxable:false,
			    	dockable:false,
			    	refreshOnShow:true,
			    	style:"width:275px; height:500px;padding:1px;z-index: 9999;top: 0px;left:0px;overflow: hidden; ",
			        title:searchLayerName+"查询结果"
			      },node);
			    var toolbar = new  dijit.Toolbar();
			      toolbar.addChild(new dijit.form.Button({label :"导出excel",iconClass :"dijitIconTable",onClick:function(){
			    	  exportExcelF(dataGrid,searchLayerName);
			      }}));
			      toolbar.addChild(new dijit.form.Button({label :("总条目:"+findResults.length)}));
			      floatingPane.addChild(toolbar);
			      floatingPane.addChild(dataGrid);
			      floatingPane.startup();
			      dataGrid.set("store", memStore);
			      if(progressBarDialog) {
			    	  progressBarDialog.hide();
			      }
			      dataGrid.on("dgrid-select", function(e) {
			    	  var row =  e.rows[0];
			    	  var query = new Query();
			  		  query.returnGeometry = true;
			  		  query.outFields = [ "*" ];
			          query.objectIds = [row.data.OBJECTID];
			          map.graphics.clear();
			          map.infoWindow.hide();
			    	  queryTask.execute(query,function (featureSet) {
			    		  setFeatureSetInMap(featureSet.features,true);
						});
			      });  
			});
};

//对地图进行初始化
function listfacilityAll(searchLayerId,searchLayerName) {
	progressBarDialog = dojoProgressBar("正在查询");
	   var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer/"+ searchLayerId; 
	   var queryTask = new QueryTask(searchurl);
		  var query = new Query();
		    query.outFields = [ "*" ];
			query.returnGeometry = false;
			query.where = "1 = 1"; 
			//map.setLevel(5);
			//console.debug("listfacilityGrid: ", searchText +"searchLayerId:"+searchLayerId);
			queryTask.execute(query,function (featureSet) {
				var results = featureSet.features;
				var columns = buildColumns(featureSet.fieldAliases);
				var data = arrayUtils.map(results, function (feature) {
				    return feature.attributes;
				});
	            var memStore = new Memory({
	                data: data,
	                idProperty: "OBJECTID"
	              });
				var dataGrid = new (declare([Grid, Selection]))({
				    bufferRows: Infinity,
				      pagingLinks: true,
	                 pagingTextBox: true,
	                 firstLastArrows: false,
	                 style:" height:300px;",
	                 pageSizeOptions: [10, 15, 25],
				    columns: columns,
			    	id:"listfacilityGrid",
				    selectionMode: "single",
				    "class": "listfacilityGrid"
				});
				var node = document.createElement('div');
				dojo.body().appendChild(node);
				var floatingPane =dijit.byId("floatingPane");
				if(floatingPane) {
					floatingPane.destroyRecursive();
				}
			    var floatingPane = new dojox.layout.FloatingPane({
			    	draggable:true,
			    	closable :true,
			    	resizable:false,
			    	maxable:false,
			    	dockable:false,
			    	id:"floatingPane",
			    	refreshOnShow:true,
			    	style:"width:275px; height:500px;padding:5px;z-index: 9999;top: 0px;left:0px;overflow: hidden; ",
			        title:searchLayerName+"查询结果"
			      },node);
			    var toolbar = new  dijit.Toolbar();
			      toolbar.addChild(new dijit.form.Button({label :"导出excel",iconClass :"dijitIconTable",onClick:function(){
			    	  exportExcelF(dataGrid,searchLayerName);
			      }}));
			    //  toolbar.addChild(new dijit.form.Button({label :("总条目:"+results.length)}));
			      floatingPane.addChild(toolbar);
			      floatingPane.addChild(dataGrid);
			      floatingPane.startup();
			      dataGrid.set("store", memStore);
			      if(progressBarDialog) {
			    	  progressBarDialog.hide();
			      }
			      dataGrid.on("dgrid-select", function(e) {
			    	  var row =  e.rows[0];
			    	  var query = new Query();
			  		  query.returnGeometry = true;
			  		  query.outFields = [ "*" ];
			          query.objectIds = [row.data.OBJECTID];
			          map.graphics.clear();
			          map.infoWindow.hide();
			    	  queryTask.execute(query,function (featureSet) {
			    		  setFeatureSetInMap(featureSet.features,true);
						});
			      });  
			});
};


//对地图进行初始化
ssmap.tjfacilityGrid = function tjfacilityGrid(searchLayerId,searchLayerName) {
	progressBarDialog = dojoProgressBar("正在统计");
	   var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer/"+ searchLayerId; 
	   var queryTask = new QueryTask(searchurl);
		  var query = new Query();
		    query.outFields = [ "*" ];
			query.returnGeometry = false;
			query.where = "1 = 1"; 
			   var statisticDefinition = new StatisticDefinition();
			   statisticDefinition.statisticType = "sum";
			   statisticDefinition.onStatisticField = "Shape_Length";
			   statisticDefinition.outStatisticFieldName = "glhl";
			   query.outStatistics = [ statisticDefinition ];
			   
			//map.setLevel(5);
			//console.debug("listfacilityGrid: ", searchText +"searchLayerId:"+searchLayerId);
			queryTask.execute(query,function (featureSet) {
				var results = featureSet.features;
				var columns = buildColumns(featureSet.fieldAliases);
				var data = arrayUtils.map(results, function (feature) {
				    return feature.attributes;
				});
	            var memStore = new Memory({
	                data: data,
	                idProperty: "OBJECTID"
	              });
				var dataGrid = new (declare([Grid, Selection]))({
				    bufferRows: Infinity,
				      pagingLinks: true,
	                 pagingTextBox: true,
	                 firstLastArrows: false,
	                 style:" height:300px;",
	                 pageSizeOptions: [10, 15, 25],
				    columns: columns,
			    	id:"listfacilityGrid",
				    selectionMode: "single",
				    "class": "listfacilityGrid"
				});
				var node = document.createElement('div');
				dojo.body().appendChild(node);
				var floatingPane =dijit.byId("floatingPane");
				if(floatingPane) {
					floatingPane.destroyRecursive();
				}
			    var floatingPane = new dojox.layout.FloatingPane({
			    	draggable:true,
			    	closable :true,
			    	resizable:false,
			    	maxable:false,
			    	dockable:false,
			    	id:"floatingPane",
			    	refreshOnShow:true,
			    	style:"width:550px; height:348px;padding:5px;z-index: 9999;top: 0px;left:0px;overflow: hidden; ",
			        title:searchLayerName+"查询结果"
			      },node);
			      floatingPane.addChild(new dijit.form.Button({label :"导出excel",iconClass :"dijitIconTable",onClick:function(){
			    	  exportExcelF(dataGrid,searchLayerName);
			      }}));
			      floatingPane.addChild(dataGrid);
			      floatingPane.startup();
			      dataGrid.set("store", memStore);
			      if(progressBarDialog) {
			    	  progressBarDialog.hide();
			      }
			      dataGrid.on("dgrid-select", function(e) {
			    	  var row =  e.rows[0];
			    	  var query = new Query();
			  		  query.returnGeometry = true;
			  		  query.outFields = [ "*" ];
			          query.objectIds = [row.data.OBJECTID];
			          map.graphics.clear();
			          map.infoWindow.hide();
			    	  queryTask.execute(query,function (featureSet) {
			    		  setFeatureSetInMap(featureSet.features,true);
						});
			      });  
			});
};

function buildColumns(attributes) {
    var columns = [];
    for (var attribute in attributes) {
        if (attributes.hasOwnProperty(attribute)) {
            var objects = {};
            if (attribute === "Shape") {
            	continue
            }
            if (attribute === "照片") {
            	continue
            }
            if (attribute === "采集日期") {
            objects.formatter=pengtu.formatterDate;
            }
            objects.label = attribute;
            objects.field = attribute;//base64.encode(s2b(attribute));
            if (attribute.indexOf("Leng")!=-1) {
            objects.label = "长度";
            } else if (attribute.indexOf("Area")!=-1) {
            objects.label = "面积";
            }
            columns.push(objects);
        }
    }
    return columns;
}
/**--------------业务图层的显示-------------------------*/

//对地图进行初始化
ssmap.addProject =function addProject() {
	ssmap.tb.activate(esri.toolbars.Draw.POLYGON);
	domStyle.set(dom.byId("ssmapdiv_container"),"cursor","pointer");
	ssmap.drawType ="11";
};
function doAddProject(evt) {
	 var graphic = new Graphic(evt.geometry);
	 setGraphicSymbol(graphic)
	 var point = getGeometryCenter(evt.geometry);
	map.graphics.add(graphic);
	  var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/bj/MapServer/4";  
	  var queryTask=new QueryTask(searchurl);
	  var dist = {};
	  var query = new Query();
		query.outFields = [ "*" ];
		query.geometry = evt.geometry;
		queryTask.execute(query,function (featureSet) {
			 var results = featureSet.features;
			 var feature = results[0];
		    if(feature) {
			     var streeId = feature.attributes["StreetId"];
			     dist.district = encodeURI(Pengtu.buildCodeName(2033,streeId.substr(0,6)));
			     dist.subdistrict = encodeURI(feature.attributes["StreetName"]); 
			 }
		    var titlePane = new dijit.Dialog({
		    	style:"width:600px;height:400px;",
		    	id:"newedit_pro",
		    	draggable:true,
		    	modal:true,
		    	showTitle:true,
				onHide : function() {
					this.destroyRecursive();
				},
				sizeMethod:"combine",
		        title:'工程预备库',
		        href:appConfig.contPath+'/mp/projectinfo!input2.action?district='+dist.district+'&subdistrict='+dist.subdistrict+'&geoLocation='+JSON.stringify(evt.geometry.toJson())+'&lon='+point.getLongitude()+'&lat='+point.getLatitude()
		      });
		      titlePane.startup();
		      titlePane.show();
			});
  	domStyle.set(dom.byId("ssmapdiv_container"),"cursor","default"); 
};

//路政许可
ssmap.addCase =function addCase() {
	ssmap.tb.activate(esri.toolbars.Draw.POLYGON);
	domStyle.set(dom.byId("ssmapdiv_container"),"cursor","pointer");
	ssmap.drawType ="12";
};
function doAddCase(evt) {
	 var graphic = new Graphic(evt.geometry);
	 setGraphicSymbol(graphic)
	 var point = getGeometryCenter(evt.geometry);
	    map.graphics.add(graphic);
	  var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/bj/MapServer/4";  
	  var queryTask=new QueryTask(searchurl);
	  var dist = {};
	  var query = new Query();
		query.geometry = evt.geometry;
		query.returnGeometry = false;
		 query.where = " 1 = 1";
		 query.outFields = [ "*" ];
		queryTask.execute(query,function (featureSet) {
			 var results = featureSet.features;
			 var feature = results[0];
		    if(feature) {
			     var streeId = feature.attributes["StreetId"];
			     dist.district = encodeURI(Pengtu.buildCodeName(2033,streeId.substr(0,6)));
			     dist.subdistrict = encodeURI(feature.attributes["StreetName"]); 
			 }
		    var titlePane = new dijit.Dialog({
		    	id:"newHidvaysaddcase",
		    	style:"width:600px",
		    	draggable:true,
		    	modal:true,
		    	showTitle:true,
				onHide : function() {
					this.destroyRecursive();
				},
				sizeMethod:"combine",
		        title:'新增路政许可',
		        href:appConfig.contPath+'/yh/high/highwaysdig!input.action?district='+dist.district+'&subdistrict='+dist.subdistrict+'&geoLocation='+JSON.stringify(evt.geometry.toJson())+'&lon='+point.getLongitude()+'&lat='+point.getLatitude()
		      });
		      titlePane.startup();
		      titlePane.show();
			});

  	domStyle.set(dom.byId("ssmapdiv_container"),"cursor","default"); 
};
//对地图进行初始化  市民投诉
ssmap.addComplaints =function addComplaints() {
	ssmap.tb.activate(esri.toolbars.Draw.POINT);
	domStyle.set(dom.byId("ssmapdiv_container"),"cursor","pointer");
	ssmap.drawType ="13";
};
function doAddComplaints(evt) {
	 var graphic = new Graphic(evt.geometry);
	 	setGraphicSymbol(graphic)
	    map.graphics.add(graphic);
	 	 var point = getGeometryCenter(evt.geometry);
		  var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/bj/MapServer/4";  
		  var queryTask=new QueryTask(searchurl);
		  var dist = {};
		  var query = new Query();
			query.outFields = [ "*" ];
			query.geometry = evt.geometry;
			queryTask.execute(query,function (featureSet) {
				 var results = featureSet.features;
				 var feature = results[0];
			    if(feature) {
				     var streeId = feature.attributes["StreetId"];
				     dist.district = encodeURI(Pengtu.buildCodeName(2033,streeId.substr(0,6)));
				     dist.subdistrict = encodeURI(feature.attributes["StreetName"]); 
				 }
			    var titlePane = new dijit.Dialog({
			    	style:"width:600px",
			    	draggable:true,
			    	id:"newComplaints",
			    	modal:true,
			    	showTitle:true,
					onHide : function() {
						this.destroyRecursive();
					},
					sizeMethod:"combine",
			        title:'新增市民投诉记录',
			        href:appConfig.contPath+'/yh//public/publiccomplaints!input.action?district='+dist.district+'&subdistrict='+dist.subdistrict+'&geoLocation='+JSON.stringify(evt.geometry.toJson())+'&lon='+point.getLongitude()+'&lat='+point.getLatitude()
			      });
			      titlePane.startup();
			      titlePane.show();
				});
  	domStyle.set(dom.byId("ssmapdiv_container"),"cursor","default"); 
};



/**-------------------地图基本操作 ---------------------------*/
// 变化地图
function resizeMap(){
	 if(map!=null) {
		 map.resize();
	 }
}
//全图
ssmap.zoomToFullExtent =function zoomToFullExtent() {
	setupAllToOrigin();
	ssmap.navToolbar.zoomToFullExtent();
}
//平移
ssmap.zoomPan =function zoomPan() {
	ssmap.navToolbar.activate(esri.toolbars.Navigation.PAN);
}
//放大
ssmap.zoomIn =function zoomIn() {
	ssmap.navToolbar.activate(Navigation.ZOOM_IN);
}
//缩小
ssmap.zoomOut = function zoomOut() {
	ssmap.navToolbar.activate(Navigation.ZOOM_OUT);
}
//清除
ssmap.cleanAll  =function cleanAll() {
	ssmap.cleanPano();
	ssmap.cleanLocate();
	map.graphics.clear();
	ssmap.tb.deactivate();
	cleanSinglePano();
	map.infoWindow.hide();
	setupAllToOrigin();
	ssmap.measurementPane&&ssmap.measurementPane.close();
}
// 街景显示清除
ssmap.cleanPano = function () {
	ssmap.panoCar&&ssmap.panoCar.remove(); 
	ssmap.isPano = false;
	dijit.byId("panoButton").setChecked(false);
	domStyle.set(dom.byId("ssmapdiv_container"),"cursor","default"); // 街景选择模式清除;
	domStyle.set(dom.byId("kisser"),"visibility","hidden");
	map.removeLayer(carLayer);
}

//单点全景清除
function cleanSinglePano () {
	ssmap.isSinglePano = false;
	map.removeLayer(singlePanoLayer);
}

      // 处理画图事件
function addGraphics(evt) {
	switch (ssmap.drawType) {
	  case "0": //清除
		map.graphics.clear();
		ssmap.tb.deactivate();
		break;
	  case "1"://标注
		ssmap.tb.deactivate();
		break;
	  case "11"://gongc
		 doAddProject(evt);
		 ssmap.tb.deactivate();
			break;
	  case "12"://破挖
		doAddCase(evt);
		 ssmap.tb.deactivate();
			break;
	  case "13"://投诉
		  doAddComplaints(evt);
			ssmap.tb.deactivate();
			break;
	  case "14"://投诉
		    doAddCorrection(evt);
			ssmap.tb.deactivate();
			break;
	  default:
		 // ssmap.tb.deactivate();
		break;
	}
}
//测量
ssmap.measure = function () {
	if(ssmap.measurementPane) {  // 已经打开了测量的控件
		return;
	}
	ssmap.drawType = "measure";
	var node = document.createElement('div');
	dojo.body().appendChild(node);
	var measurement = new Measurement({
	    map: map,
	    defaultAreaUnit:esri.Units.SQUARE_METERS,
	    defaultLengthUnit:esri.Units.METERS
	  });
	ssmap.measurementPane = new dojox.layout.FloatingPane({
    	draggable:false,
    	closable :true,
    	resizable:false,
    	maxable:false,
    	dockable:false,
    	refreshOnShow:true,
    	style:"width:210px; height:160px;padding:5px;z-index: 9999;top: 65px;right:15px;overflow: hidden; "
      },node);
	ssmap.measurementPane.addChild(measurement);
	ssmap.measurementPane.startup();
    on(ssmap.measurementPane,"Unload",function () {
    	  ssmap.drawType = "99";
    	  this.destroyRecursive();
    	  ssmap.measurementPane =null;
      });
}

/**
 * 将所有全局变量还原到初始化状态
 */
function setupAllToOrigin() {
	//ssmap.navToolbar.activate(esri.toolbars.Navigation.PAN);
	ssmap.drawType = "99";
	//symbol = null;
	//ssmap.tb.deactivate();
	if (!map.isZoomSlider) {
		map.showZoomSlider();
	}
}

function addScalebar (map){
	//比例尺变化
	  var scalebar = new esri.dijit.Scalebar({
	    map: map,
	    visible:true,
	    attachTo:"bottom-left",
	    opacity:0.5,
	    scalebarStyle:"ruler",
	    scalebarUnit:'metric',
	    visible:true
	  });
	}

//infoWindow 增加数据编辑功能的操作;
function addCorrectionAction () {
 var detailsLink = dojo.create("a", {  
        "class": "action panoTo",  
        "innerHTML": "数据编辑",  
        "href": "javascript:void(0);"  
    }, dojo.query(".actionList", map.infoWindow.domNode)[0]);  
    on(detailsLink, "click", function (evt) {  
       var feature = map.infoWindow.getSelectedFeature();  
       var point = getGeometryCenter(feature.geometry);
       ssmap.correction(point);
    });  
}
//数据编辑 操作
ssmap.correction  =function (point) {
    var titlePane = new dijit.Dialog({
    	style:"width:300px;height:275px;",
    	draggable:true,
    	id:"correctiond",
    	modal:true,
    	showTitle:true,
		onHide : function() {
			this.destroyRecursive();
		},
		sizeMethod:"combine",
        title:'数据编辑',
        href:appConfig.contPath+'/app/correction_input.action?facilityName=地图&geoLocation='+JSON.stringify(point.toJson())
      });
     // titlePane.placeAt(ssmap.map.root,"last");
      titlePane.startup();
      titlePane.show();
	}


//对地图进行初始化
ssmap.addCorrection =function addProject() {
	ssmap.tb.activate(esri.toolbars.Draw.POLYGON);
	domStyle.set(dom.byId("ssmapdiv_container"),"cursor","pointer");
	ssmap.drawType ="14";
};

function doAddCorrection(evt) {
	 var graphic = new Graphic(evt.geometry);
	 setGraphicSymbol(graphic)
	 //var point = getGeometryCenter(evt.geometry);
	map.graphics.add(graphic);
	ssmap.correction(evt.geometry);
}
/** -----------------------------------实景的操作程序-------------------------*/

//激活前方景观的小车图标,小车点击事件开启前方景观
ssmap.showSinglePanolayer =function showSinglePanolayer(){
	if(ssmap.isSinglePano) {
		return;
	}
    singlePanoLayer.setRenderer(new esri.renderer.SimpleRenderer(singlePanoSymbol));
    map.addLayer(singlePanoLayer);
    on(singlePanoLayer, "click", function(evt){
    	showSinglePano(evt.graphic.attributes["Guid"])
    });
    ssmap.isSinglePano =true;
    searchSinglePano();
}

//列出所有的单点全景的列表  并能能够点击查询
function searchSinglePano() {
    var query = new Query();
    query.outFields = ["*"];
    query.where = " 1 = 1";
     // 查询
    singlePanoLayer.queryFeatures(query, function (featureSet) {
        if(!ssmap.singlePanoGrid) {
        	ssmap.singlePanoGrid = new (declare([Grid,Selection]))({
         	    selectionMode: "single",
         	    bufferRows:Infinity,
                 idProperty:"id",
                 keepScrollPosition:false,
                 bufferRows: Infinity,
                 columns: [{
                     label: "序号",
                     className:"index",
                     field: "index"
                 },{
                     label: "360°全景地址",
                     field: "dd"
                 }
                 ]
               }, "singlePanoDiv");
        }
    	var data = arrayUtils.map(featureSet.features, function(graphic,index) {
            return {
              "index":index+1,
              "id":graphic.attributes["FID"],
              "Guid":graphic.attributes["Guid"],
              "dd": graphic.attributes["Name"] 
            }
          });
    	 var memStore = new Memory({ data: data });
    	 ssmap.singlePanoGrid.set("store", memStore);
	   	 ssmap.singlePanoGrid.on("dgrid-select", function(evt){
	  		var row =  evt.rows[0];
	  		var query = new Query();
            query.objectIds = [row.id];
            singlePanoLayer.selectFeatures(query, FeatureLayer.SELECTION_NEW, function(features) {
              if (features.length ) {
            	  var centerpoint =getGeometryCenter(features[0].geometry);
            	  if( map.getLevel()<8) {
      			    map.centerAndZoom(centerpoint,8);
      			} else {
      				map.centerAt(centerpoint);
      			}
            	  showSinglePano(row.data.Guid,row.data.dd)
              } 
            });
	  	});
    });
}

function showSinglePano (guid,title) {
	  if(!guid){
		  alert("无单点全景");
		  return;
	  }
	  if(!title){
		  title ="360°单点全景"
	  }
	var url = appConfig.singleURL+"?guid="+guid;
    var titlePane = new dojox.widget.Dialog({
    	style:"padding: 5px; margin: 0; left: 0; top: 0;",
    	draggable:true,
    	modal:true,
    	title:title,
    	showTitle:true,
    	sizeToViewport:true,
    	draggable:true,
    	maxRatio:10,
    	isLayoutContainer:false,
    	refreshOnShow:true,
    	parseOnLoad:true,
    	modal:true,
		onHide : function() {
			this.destroyRecursive();
		},
		content:'<iframe  src="'+url+'" style="width:99%; height:98.5%;" scrolling="no"></iframe>',
		sizeMethod:"combine"
      });
     // titlePane.placeAt(ssmap.map.root,"last");
      titlePane.startup();
      titlePane.show();
	
} 


//激活前方景观的小车图标,小车点击事件开启前方景观
ssmap.showPanolayer =function showPanolayer(){
    map.infoWindow.hide();
    map.graphics.clear();  // 地图清理
    ssmap.panoCar=on(ssmap.map, "mouse-move", function(e){  // 小图标鼠标移动跟随
		//console.log(e.clientX +"dd"+e.clientY )
		domStyle.set(dom.byId("kisser"),"visibility","visible");
		domStyle.set(dom.byId("kisser"),"top",(e.clientY-35)+"px");
		domStyle.set(dom.byId("kisser"),"left",(e.clientX-300)+"px");
		domStyle.set(dom.byId("ssmapdiv_container"),"cursor","pointer");
	  });
    carLayer.setRenderer(new esri.renderer.SimpleRenderer(highlightSymbol));
    map.addLayer(carLayer);
    //点击小车开启前方景观
    ssmap.isPano =true;
   on(carLayer, "click", showPanoInfo);
}
// infoWindow 增加操作显示当前实景影像的操作;
function addPanoAction () {
 var detailsLink = dojo.create("a", {  
        "class": "action panoTo",  
        "innerHTML": "实景影像",  
        "href": "javascript:void(0);"  
    }, dojo.query(".actionList", map.infoWindow.domNode)[0]);  
    on(detailsLink, "click", function (evt) {  
       var feature = map.infoWindow.getSelectedFeature();  
       console.debug("getSelectedFeature",feature);
       var point = getGeometryCenter(feature.geometry);
       ssmap.trueMapInf(point.getLongitude(),point.getLatitude());
    });  
}

function  addBasemapGallery() {
	 var basemaps = [];
     var fsjtLayer = new esri.dijit.BasemapLayer({
       url:appConfig.gisPath+"/arcgis/rest/services/fsjt/bj/MapServer"
     });
     var fsjtBasemap = new esri.dijit.Basemap({
       layers      :[fsjtLayer],
       title       :"佛山地图",
       thumbnailUrl:appConfig.contPath+"/images/gis/basemap/fsjt.png"
     });
     basemaps.push(fsjtBasemap);
     var osmLayer = new esri.dijit.BasemapLayer({
    	 type:"OpenStreetMap"
     });
     var osmBasemap = new esri.dijit.Basemap({
       layers      :[osmLayer],
       title       :"街道地图",
       thumbnailUrl:appConfig.contPath+"/images/gis/basemap/osm.png"
     });
     basemaps.push(osmBasemap);
     var imageryLayer = new esri.dijit.BasemapLayer({
    	 url:"http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer"
     });
     var imageryBasemap = new esri.dijit.Basemap({
       layers      :[imageryLayer],
       title       :"影像地图",
       thumbnailUrl:appConfig.contPath+"/images/gis/basemap/tempimagery.jpg"
     });
     basemaps.push(imageryBasemap);
     var basemapGallery = new esri.dijit.BasemapGallery({
       showArcGISBasemaps:false,
       basemaps          :basemaps,
       map               :map
     }, "basemapGallery");
	 var selectionHandler = dojo.connect(basemapGallery,"onSelectionChange",function(){
         dojo.disconnect(selectionHandler);
       });
       basemapGallery.startup();
	
}
/*
 *开启实景影像
**/
function showPanoInfo(ev){ 
	  // map.centerAt(ev.mapPoint); //point.getLongitude(),point.getLatitude()
	   ssmap.trueMapInf(ev.mapPoint.getLongitude(),ev.mapPoint.getLatitude());
}
//显示实景
ssmap.trueMapInf =function trueMapInf(x ,y) {
	 var dil = registry.byId("trueMapD");
	  dil.show();
	  showVisionByLngLat(x,y);
	 // ssmap.detailTotalRoadInfo();
};
//缩略图
ssmap.createHandlerMap =function () {
	if(!ssmap.handlerMap){
ssmap.handlerMap = handlerMap= new Map("handlerMap", { 
    zoom: 18,
    nav:false,
    logo:false,
    slider: false
  });
ssmap.handlerMap.addLayers([baseViewmap,basedRefmap]);
	}
   return handlerMap;
}
//原来的实景位置
ssmap.centerAtLastPanoMap =function () {
		if(ssmap.panoPoint){ 
			if(ssmap.lastPano){
				ssmap.map.graphics.remove(ssmap.lastPano);
				ssmap.map.infoWindow.hide();
			}
			ssmap.lastPano =  new esri.Graphic(ssmap.panoPoint, lastPanoSymbol);
			ssmap.map.graphics.add(ssmap.lastPano);
			 var deferred =ssmap.map.centerAndZoom(ssmap.panoPoint,18);
//			   deferred.then(function(value){
//					var centrPoint =ssmap.panoPoint;
//					var screenPoint = map.toScreen(centrPoint);
//					map.infoWindow.setTitle("刚才在这里");
//			        map.infoWindow.setContent("");
//			        map.infoWindow.show(centrPoint,map.getInfoWindowAnchor(screenPoint));
//				  });
			var infoTemplate = new esri.InfoTemplate("刚才在这里", "");
			ssmap.lastPano.setInfoTemplate(infoTemplate);
			ssmap.map.infoWindow.setContent(ssmap.lastPano.getContent());
	        //ssmap.map.infoWindow.resize(150,20);
		}
}

//中心点移动图标
ssmap.centerAtHandlerMap =function (lon,lat,yaw) {
		var pt = new Point(lon,lat,ssmap.spatialReference);
		ssmap.panoPoint = new Point(lon,lat,ssmap.spatialReference);
		if(ssmap.car==null){ 
			ssmap.car = new esri.Graphic(pt, monkeySymbol);
		}
		//console.debug("yawyawyawyawyawyawyaw:",yaw)
		var newYaw  = parseInt((yaw+360)%360/30);
		monkeySymbol.setUrl(appConfig.contPath+"/images/gis/monkey/monkey_"+newYaw+".png");
		ssmap.car.setGeometry(pt);
		handlerMap.graphics.add(ssmap.car);
		handlerMap.centerAt(pt);
}
ssmap.resizeHandlerMap =function () {
	handlerMap.resize();
}

//对地图进行初始化
function initFunctionality(map) {
	ssmap.navToolbar = new Navigation(ssmap.map);
	ssmap.tb = tb= new esri.toolbars.Draw(ssmap.map);
	ssmap.editToolbar= editToolbar = new Edit(map);
	on(ssmap.tb, "draw-end", addGraphics);
	addPanoAction();
	addCorrectionAction();
	addBasemapGallery();
	createGraphicsMenu();
	//createMapMenu();
};
on(map, "load", initFunctionality);



//----------------综合查询功能------------------------------//////////



//查询道路
ssmap.searchFacilityRoad = function (searchtext) {
	if(!searchtext) {
		return;
	}
	  var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer";  
	var findParams = new FindParameters(); 
        findParams.returnGeometry = true; 
        findParams.layerIds = [51,52,53]; 
        findParams.searchFields = ["道路名称","道路编号","行政区划","所属镇街"];
        findParams.searchText = searchtext; 
        function roadFormatter(item){
			return "<h4>" + item.index + ": " + item.dlbh + "</h4><p>" +
				item.dlm + "("+ item.dlfj +", "+ item.xzjd+")</p>";
		}
        var findTask = new esri.tasks.FindTask(searchurl);
        var columns = [{
            label: "查询结果",
            formatter: roadFormatter,
            field: "_item"
        }
        ]
        if(!ssmap.roadGrid) {
        	ssmap.roadGrid = new (declare([Grid,Pagination,Selection]))({
         	    selectionMode: "single",
                 idProperty:"id",
                 getBeforePut: false,
                 columns:columns
               }, "roadsearch");
        } else {
        	 ssmap.roadGrid.set("columns",columns);
        }
        
        findTask.execute(findParams, function(findResults){
        	if(findResults.length==0){
        		return;
        	}
            map.graphics.clear();
            map.infoWindow.hide();
        	var data = arrayUtils.map(findResults, function(findResult,index) {
        		var graphic = findResult.feature;
    				setGraphicSymbol(findResult.feature);
    				summaryInfo(graphic);
    				map.graphics.add(graphic);
                return {
                  // property names used here match those used when creating the dgrid
                  "layerId":findResult.layerId,
                  "index":index+1,
                  "id":findResult.feature.attributes["OBJECTID"],
                  "dlm": findResult.feature.attributes["道路名称"], 
                  "dlbh": findResult.feature.attributes["道路编号"],
                  "xzjd": findResult.feature.attributes["街道"],
                  "dlcd": findResult.feature.attributes["道路长度"],
                  "dlfj": findResult.feature.attributes["道路分级"],
                  "dllx": findResult.feature.attributes["路面类型"]
                }
              });
        	  var memStore = new Memory({ data: data });
        	  ssmap.roadGrid.set("store", memStore);
        	  ssmap.roadGrid.on("dgrid-select", function(evt){
            		var row =  evt.rows[0];
            		ssmap.map.infoWindow.hide();
            		var findParams = new esri.tasks.FindParameters();
            		var findTask = new esri.tasks.FindTask(searchurl);
            		findParams.returnGeometry = true; 
            		findParams.layerIds = [row.data.layerId]; 
            		findParams.searchFields = ["OBJECTID"];
            		findParams.searchText = row.id; 
            		ssmap.dlbh = row.data.dlbh;
            		var layerId = ssmap.layerId;
            		if(!layerId) {
            			layerId = 47;
            		}
            		ssmap.listTabFGrid(layerId);
            		findTask.execute(findParams, showSingleRoad);
            	});
        }); 
      
	}



//对地图进行初始化
ssmap.listTabFGrid =function listTabFGrid(layerId) {
	  var dlbh = ssmap.dlbh;
	  if(!(layerId&&dlbh)) {
		  return ;
	  }
	
	   var searchurl = appConfig.gisPath+"/arcgis/rest/services/fsjt/ss/MapServer/"+ layerId; 
	   var queryTask = new QueryTask(searchurl);
		  var query = new Query();
			query.returnGeometry = true;
			//query.geometry= map.extent;
			query.outFields = [ "*" ];
			if(layerId==33) {
				dlbh = dlbh.substr(1,8);
				query.where = "桥梁编码 like '%"+ dlbh+"%'"; 
			} else {
				query.where = "编码 = '"+ dlbh+"'"; 
			}
			queryTask.execute(query,function (featureSet) {
				var results = featureSet.features;
				var columns = buildColumns(featureSet.fieldAliases);
				var data = arrayUtils.map(results, function (feature) {
				    return feature.attributes;
				});
	            var memStore = new Memory({
	                data: data,
	                idProperty: "OBJECTID"
	              });
	            
	            var dataGridId= "sscxG"+layerId;
				var floatingPane = registry.byId("sscx"+layerId);
				var congPane = registry.byId(dataGridId);
				if(congPane){
					congPane.destroyRecursive();
				}
				congPane =  new dijit.layout.ContentPane({
					 style:"padding: 0; margin: 0; left: 0; top: 0; width: 100%;height: 100%;",
					 id:dataGridId
				})
			    //console.debug("dataGrid：",floatingPane.getChildren());
				floatingPane.addChild(congPane);
				//console.debug("测试：",floatingPane.hasChildren());
				var dataGrid = new (declare([Grid, Selection]))({
						  bufferRows: Infinity,
						  pagingLinks: true,
						  pagingTextBox: true,
						  id:dataGridId,
						  firstLastArrows: false,
						  style:" height:300px;",
						  pageSizeOptions: [10, 15, 25],
						  columns: columns,
						  selectionMode: "single",
						  "class": "listfacilityGrid"
					  });
				  congPane.addChild(dataGrid);
			      dataGrid.set("store", memStore);
			      dataGrid.on("dgrid-select", function(e) {
			    	  var row =  e.rows[0];
			    	  var query = new Query();
			  		  query.returnGeometry = true;
			  		  query.outFields = [ "*" ];
			          query.objectIds = [row.data.OBJECTID];
			          map.graphics.clear();
			          map.infoWindow.hide();
			    	  queryTask.execute(query,function (featureSet) {
			    		  setFeatureSetInMap(featureSet.features,true,true);
						});
			      });  
			});
};



function createGraphicsMenu() {
    // Creates right-click context menu for GRAPHICS
    ctxMenuForGraphics = new dijit.Menu({});
    ctxMenuForGraphics.addChild(new dijit.MenuItem({ 
      label: "编辑",
      onClick: function() {
        if ( selected.geometry.type !== "point" ) {
          editToolbar.activate(Edit.EDIT_VERTICES, selected);
        } else {
          alert("Not implemented");
        }
      } 
    }));
    ctxMenuForGraphics.addChild(new dijit.MenuItem({ 
      label: "移动",
      onClick: function() {
        editToolbar.activate(Edit.MOVE, selected);
      } 
    }));
    ctxMenuForGraphics.addChild(new dijit.MenuSeparator());
    ctxMenuForGraphics.addChild(new dijit.MenuItem({ 
      label: "删除",
      onClick: function() {
        map.graphics.remove(selected);
      }
    }));

    ctxMenuForGraphics.startup();

    map.graphics.on("mouse-over", function(evt) {
      // We'll use this "selected" graphic to enable editing tools
      // on this graphic when the user click on one of the tools
      // listed in the menu.
      selected = evt.graphic;
      // Let's bind to the graphic underneath the mouse cursor           
      ctxMenuForGraphics.bindDomNode(evt.graphic.getDojoShape().getNode());
    });

}


function createMapMenu() {
    // Creates right-click context menu for map
    ctxMenuForMap = new dijit.Menu({
      onOpen: function(box) {
        // Lets calculate the map coordinates where user right clicked.
        // We'll use this to create the graphic when the user clicks
        // on the menu item to "Add Point"
        currentLocation = getMapPointFromMenuPosition(box);          
        editToolbar.deactivate();
      }
    });

    ctxMenuForMap.addChild(new dijit.MenuItem({ 
      label: "增加点",
      onClick: function(evt) {
        var symbol = new SimpleMarkerSymbol(
          SimpleMarkerSymbol.STYLE_SQUARE, 
          30, 
          new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_SOLID, 
            new Color([200,235, 254, 0.9]), 
            2
          ), new Color([200, 235, 254, 0.5]));
        var graphic = new Graphic(geometryJsonUtils.fromJson(currentLocation.toJson()), symbol);
        map.graphics.add(graphic);
      }
    }));

}

// Helper Methods
function getMapPointFromMenuPosition(box) {
  var x = box.x, y = box.y;
  switch( box.corner ) {
    case "TR":
      x += box.w;
      break;
    case "BL":
      y += box.h;
      break;
    case "BR":
      x += box.w;
      y += box.h;
      break;
  }

  var screenPoint = new Point(x - map.position.x, y - map.position.y);
  return map.toMap(screenPoint);
}



});